#region usings

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Drawing.Imaging;


using CStock;
using CUtil;
using CTrading;

using System.Threading;
using CGraph;

using EForms;
using System.Collections.Generic;
#endregion


namespace CapitalReSources
{
	/// <summary>
	/// Summary description for MainClass
	/// </summary>
	public partial class MainClass : IMainClass
	{
	

		#region menu handlers

		
		


		public void DoMenuReEvaluatesPortfolio()
		{
			this.programContext.TradeEconomy.Portfolio_Selected.ReEvaluates();
		}

		/// <summary>
		/// 
		/// </summary>
		public void DoMenuShowSelectedIndicatorValues()
		{
            if (SetSelectedShareOrPortfolio())
            {
                FillSelectedIndicatorsListView(this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected, false);
            }
		}
		
		public void DoMenuNewShare()
		{
            IPortfolio port = this.programContext.TradeEconomy.Portfolio_Selected;
			IDataClass dc = new DataClassDaily();
			//a new name: NewPortfolio + some extension
			dc.ID = "NewShare";


            
			DataItem dci = new DataItem();
            dci.Parent = port;
            dci.ObjectChanged += new ObjectChangedEvent(this.OnObjectChanged);

			dci.DataClass = dc;

			dci.Parent = port;
            port.DataItems.Items.Add(dci);
            dci.Serialize();
            port.Serialize();
            ITreeViewStock selectedTreeView = GetSelectedTreeView();
            selectedTreeView.Refresh();
            selectedTreeView.Select_MainNode(port.Name);
            selectedTreeView.Select_SubNode(dci.Name);


		}
		

		/// <summary>
		/// 
		/// </summary>
		public void DoMenuNewPorfolio()
		{
			IPortfolio port = new Portfolio();
            port.StockTypePortfolio = false;
			//a new name: NewPortfolio + some extension
			port.ID = "NewPortfolio";
			
			for(int i = 1; i < 100; i++)
			{
                if (this.programContext.TradeEconomy.Portfolios[port.Name] != null)
				{
					port.ID = "NewPortfolio" + i;
				}
				else
				{
					break;
				}
			}
			port.Serialize();
			this.programContext.TradeEconomy.Portfolios.Items.Add(port);
			port.ObjectChanged += new ObjectChangedEvent(this.OnObjectChanged);
            ITreeViewStock selectedTreeView = GetSelectedTreeView();
			selectedTreeView.Refresh();
			
			
		}

		/// <summary>
		/// 
		/// </summary>
		public void DoMenuOptimize()
		{
			
			DataClass.DeSerialize(this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected.DataClass, this.programContext.Configuration.IntradayModus);

			this.tradeControl.ProgramContext = this.programContext;


			SelectTabPageAndSetProgramContext(ViewsAvailable.tradeView.ToString());

			
		}
        	/// <summary>
		/// 
		/// </summary>
        public void DoMenuProperties(object selectedNode)
		{
            TreeNodeStock node = selectedNode as TreeNodeStock;
            switch (node.TreeNodeBase)
            {
                case TreeNodeInfo.PORTFOLIO:
                {
                    //this.programContext.TradeEconomy.Portfolio_Selected.DeSerialize_DataClass(this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected.DataClass, this.programContext.Configuration.IntradayModus);
                    IPortfolio portf = (IPortfolio) (node.PortfolioOrDataItem);
                    break;
                }
            case TreeNodeInfo.SHARE:
                {
                    IDataItem di = (IDataItem)(node.PortfolioOrDataItem);
                    ShowFinancialData(di);
                    break;
                }
            }
            //node.BaseType
            string shareName = node.Text;


		

			SelectTabPageAndSetProgramContext(ViewsAvailable.dataView.ToString());

			
		}
        
		/// <summary>
		/// 
		/// </summary>
		public void DoMenuToolsCustomize()
		{
			FormCustomize formCustomize = new FormCustomize();
			formCustomize.ShowDialog();
		}
		/// <summary>
		/// 
		/// </summary>
		public void DoMenuToolsOptions()
		{
			//20020612 Options options = new Options();
			FormOptions formOptions = new FormOptions("",this.gridDataView,new DataGridClass(),this.programContext);
			try
			{
				formOptions.ShowDialog();
			}
			catch(Exception e)
			{
				System.Diagnostics.Debug.Assert(false , "Error showing configuration dialog - perhaps the date configured is wrong ? ",e.Message);
			}
		}
        public void DoMenuResetConfiguration()
		{
            //string appPath = System.Windows.Forms.Application.StartupPath;
            //string appPath = System.Windows.Forms.Application.UserAppDataPath;
            string appPath = AppDomain.CurrentDomain.BaseDirectory;
            



            CStock.ProgramContext.Reg_ResetLastPath();
            this.programContext = CStock.ProgramContext.CreateProgramContext(appPath, "Default", true);
            this.UpdateViewCurrentPath();

            



		}

        public void DoMenuUpdateStandardPorfolio_Names()
        {
            this.View.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            this.quoteUpdater.UpdateStandardPorfolio_Names();
            this.View.Cursor = System.Windows.Forms.Cursors.Default;
        }
        public void DoMenuUpdateStandardPorfolio_Quotes()
        {
            this.View.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            this.quoteUpdater.UpdateStandardPorfolio_OnlyQuotes();
            this.View.Cursor = System.Windows.Forms.Cursors.Default;
        }
        
        public void DoMenuUpdateResetAllStandardPorfolios()
		{
            this.View.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            this.quoteUpdater.GetSpecialDataForPortfolio();

            //return false;
            this.View.Cursor = System.Windows.Forms.Cursors.Default;
		}
     
        
		/// <summary>
		/// DoMenuHelpAbout
		/// </summary>
		public void DoMenuHelpAbout()
		{
			FormAbout formAbout = new FormAbout();
			formAbout.ShowDialog();
		}
	
	
		public void DoModeUserTrade()
		{

			TreeNodeStock selectedNode = GetSelectedNode();
			
			
			SelectTabPageAndSetProgramContext(ViewsAvailable.tradeView.ToString());

			this.tradeControl.ProgramContext = this.programContext;

			switch (selectedNode.TreeNodeBase)
			{
				case TreeNodeInfo.PORTFOLIO:
				{
                    
					return ;
				}
				case TreeNodeInfo.SHARE:
				{
                    DataClass.DeSerialize(this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected.DataClass, this.programContext.Configuration.IntradayModus);
					
					SelectTabPageAndSetProgramContext(ViewsAvailable.tradeView.ToString());

					break;

				}
				default:
				{
                    DataClass.DeSerialize(this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected.DataClass, this.programContext.Configuration.IntradayModus);
					SelectTabPageAndSetProgramContext(ViewsAvailable.tradeView.ToString());

					return ;
				}
			}

		}

		public void DoStopAction()
		{
			try
			{
				Debug.WriteLine("MainClass - Terminating Action! ");
				this.programContext.Configuration.TerminateAction = true;
			}
			catch (Exception exc)
			{
				Debug.WriteLine("MainClass - Error terminating Action: " + exc.Message);
			}
		}

	

	
		
		public void DoMenuPortfolio_Delete()
		{
            ITreeViewStock selectedTreeView = GetSelectedTreeView();
            selectedTreeView.DeleteSelectedNode();

		}
	
		public void DoMenuResetPortfolioTrade()
		{
			this.programContext.TradeEconomy.Portfolio_Selected.ResetTradings();
			this.RefreshTree();
		}
		public void DoMenuResetPortfolio_Empty()
		{
			this.programContext.TradeEconomy.Portfolio_Selected.Reset_Empty();
			this.RefreshTree();
		}
		public void DoMenuRefreshPortfolio()
		{
			this.programContext.TradeEconomy.Portfolio_Selected.RefreshShareData();
		}
	

	
	
		public void DoModeUserTrade(bool enter)
		{
			IListQuotes qColl = this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected.DataClass.QuoteCollection;

			if(enter)
			{
				this.programContext.Configuration.Dates.DateMinUserTrade = qColl[0].DATE;
				this.programContext.Configuration.Dates.DateMaxUserTrade = qColl[0].DATE;
				this.programContext.Configuration.Dates.DateMinChartCurrent = qColl[0].DATE;
				this.programContext.Configuration.Dates.DateMaxChartCurrent = qColl[0].DATE;
			
			}
			else
			{
				this.programContext.Configuration.Dates.DateMinUserTrade = this.programContext.Configuration.Dates.DateMinReset;
				this.programContext.Configuration.Dates.DateMaxUserTrade = this.programContext.Configuration.Dates.DateMaxReset;

				this.programContext.Configuration.Dates.DateMinSimulation = this.programContext.Configuration.Dates.DateMinReset;
				this.programContext.Configuration.Dates.DateMaxSimulation = this.programContext.Configuration.Dates.DateMaxReset;

				
			}
			//this.DoMenuChartShare();
		}
		public void DoMenuShowTradeEvents(bool simulationPortfolio)
		{
			SelectTabPageAndSetProgramContext(ViewsAvailable.tradeView.ToString());
			ListView lv = gridTrade as ListView;
			lv.Items.Clear();
			this.gridTrade.CreateGrid(CUtil.GridTypes.TradeEvent, true);
			//UpgradeGrid
			//this.gridTrade.WriteTradeEvents(simulationPortfolio);
		}
	
	
		public void DoMenuRefreshShareItems()
		{
            try
            {
                this.programContext.Trader_Simulation.RefreshShareItems();
                this.RefreshTree();
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error refreshing share items " + ex.Message);
            }
			
		}
        public void DoMenuUpdateFinancialData()
		{
            Thread updateThread = new Thread(new ThreadStart(UpdateFinancialData));
            updateThread.Start();

		}
        public void DoMenuUpdateFundamentalData_Years()
		{
            Thread updateThread = new Thread(new ThreadStart(UpdateFundamentalData_Years));
            updateThread.Start();

		}
        public void DoMenuUpdateFundamentalData_Quarter()
        {
            Thread updateThread = new Thread(new ThreadStart(UpdateFundamentalData_Quartal));
            updateThread.Start();

        }
    
        public void DoMenuUpdateQuotes()
		{
            Thread updateThread = new Thread(new ThreadStart(UpdateQuotes));
            updateThread.Start();

		}

		public void DoMenuNetworkNeuralTest()
		{
			
			CNeural.TestNeuronalNetwork tc = new CNeural.TestNeuronalNetwork(this.programContext);

			tc.TrainNetworkNeural();
			tc.SimulateTest();
	
		}
		public void DoMenuIndicatorBuilder()
		{
			
			DialogIndicatorBuilder dib = new DialogIndicatorBuilder(this.programContext);
			dib.ShowDialog();
			//refresh available indicators !
			//IndEvaluator.IndicatorsAvailable = null;

			
		}
		public void DoMenuUpdateSymbols()
		{
			CUtil.SymbolTable_WKN sy = new SymbolTable_WKN();
			for(int i = 0; i < this.programContext.TradeEconomy.Portfolio_Selected.DataItems.Count; i++)
			{
				IDataItem di = this.programContext.TradeEconomy.Portfolio_Selected.DataItems[i];
				IDataClass dc = this.programContext.TradeEconomy.Portfolio_Selected.DataItems[i].DataClass;
                Debug.Assert(false, "SW Error : Implementation changed: DoMenuUpdateSymboly - WKN there any more");
                //string wkn =  sy.GetSymbolForWKN(di.ID);
                //di.Symbol = wkn;
            }

			this.programContext.TradeEconomy.Portfolio_Selected.Serialize();
		
		}
		
	
		public void DoMenuGetSingleQuote()
		{
			this.View.Cursor =  System.Windows.Forms.Cursors.WaitCursor;
			
		
			SelectTabPage(ViewsAvailable.dataView.ToString());


            ((IContextProvider)(this.listViewIntraday)).ProgramContext = this.programContext;
			listViewIntraday.UpdateQuotes();



			this.View.Cursor =  System.Windows.Forms.Cursors.Default;
		}

	
		
		public void DoMenuActivateIntraday()
		{
			this.View.Cursor =  System.Windows.Forms.Cursors.WaitCursor;
			
			SelectTabPage(ViewsAvailable.intradayView.ToString());



            ((IContextProvider)(this.gridIntraday)).ProgramContext = this.programContext;
			if(this.gridIntraday.CreateGrid(CUtil.GridTypes.Intraday, true))
                this.gridIntraday.FillPortfolioGrid(this.programContext.TradeEconomy.Portfolio_Selected);
			

			this.View.Cursor =  System.Windows.Forms.Cursors.Default;

		}
        public void DoMenuAddOneDay()
        {
            this.programContext.TradeEconomy.AddOneDay();
            
        }
    

	
		
	
	

		public void DoMenuReEvaluatesDataClass()
		{
			this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected.DataClass.ReEvaluates();
		
		}
	
	
		
     
		public void DoMenuChartControl (bool intraday)
		{
            try
            {
                IDataItem di = this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected;
                if (intraday)
                {
                    ChartIntradayWindow(di);
                }
                else
                {
                    ChartShareWindow(di);
                }
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "SW Error - Plotting " + ex.Message);
            }
		}
        public void DoMenuWebupdateAndChart(bool intraday)
        {
            DoMenuUpdateQuotes();
            //does not work - no double calls of web ...
            //UpdateFinancialData();

            


            IDataItem di = this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected;
            if (intraday)
            {
                ChartIntradayWindow(di);
            }
            else
            {
                ChartShareWindow(di);
            }
        }

		#endregion

        public void DoMenuIntradayQuoteLast()
        {
            this.View.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            IDataItem di = this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected;
            YahooFeedSockets.GetYahoo_RealtimeECN(di, @"http://finance.yahoo.com/q/ecn?s=");
            this.View.Cursor = System.Windows.Forms.Cursors.Default;
        }

        /// <summary>
        /// Show portfolio in grid
        /// </summary>
        public void DoTreeMenuMenuPortfolioShowInGrid()
        {
            this.View.Cursor = System.Windows.Forms.Cursors.WaitCursor;

            ShowPortfolioInStockGrid();
            ShowPortfolioFundamentalDataInGrid();

            this.View.Cursor = System.Windows.Forms.Cursors.Default;


        }
        
        public void DoMenuTreeShareShowInGrid()
        {
            ShowShareFundamentalDataInGrid();

        }
        public void DoMenuIntradayQuotes_StartGet_All()
        {
            this.View.Cursor = System.Windows.Forms.Cursors.WaitCursor;

            GetLastIntradayQuotes();
            //GetIntradayQuotesAndOnlySaveThem();


            this.View.Cursor = System.Windows.Forms.Cursors.Default;


        }
        public void DoMenuIntradayQuotes_StopGet_All()
        {
            this.yahooIntraday.StopDownload();
        }


        public void DoMenuResetPortfolioFromWeb()
        {
            this.View.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            IPortfolio port = this.programContext.TradeEconomy.Portfolio_Selected;

            //remove portfolio:
            this.programContext.TradeEconomy.Portfolios.Items.Remove(port);
            //--------------------
            this.quoteUpdater.UpdatePortfolioFromWeb(port.Name);


            this.programContext.TradeEconomy.Portfolio_Selected = port;

            //add portfolio:
            this.programContext.TradeEconomy.Portfolios.Items.Add(port);
            //this.programContext.TradeEconomy.Serialize();
            //--------------------
            //return false;
            this.View.Cursor = System.Windows.Forms.Cursors.Default;
            ITreeViewStock selectedTreeView = GetSelectedTreeView();
            selectedTreeView.UpdatePortfolioNode(port);
            //RefreshAll();


        }
        public void DoMenuIntradayQuotes_WhichQuotesFetched()
        {

        }
        public void DoMenuGetIntradayDataStart()
        {
            //this.View.Cursor = System.Windows.Forms.Cursors.WaitCursor;

            Thread updateThread = new Thread(new ThreadStart(UpdatePortfolioIntradayAndShowInGrid));
            updateThread.Start();

            //this.View.Cursor = System.Windows.Forms.Cursors.Default;


        }
        public void DoMenuGetIntradayDataStop()
        {
            this.yahooIntraday.StopDownload();
        }
        public void DoMenuChartIntraday()
        {
        }
        public bool DoMenuShowQuotes_Window()
        {
            CGrid.GridWindow gridWindow = new CGrid.GridWindow();
            gridWindow.GridBase.CreateGrid(CUtil.GridTypes.Quotes, true);

            IDataClass dcd = this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected.DataClass;
            for (int i = 0; i < dcd.QuoteCollection.Count; i++)
            {
                IQuoteBase q = dcd.QuoteCollection[i];
                gridWindow.GridBase.AddRow_Single(q, false);
            }


            //gridWindow.ShowDialog();

            gridWindow.ShowDialog();

            return true;

        }
        public ITradeSystem DoMenuTradeSystemBuySellChooseFile()
        {
            Stream myStream;

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = this.programContext.Configuration.Directories.TradeSystemsTemplatesPath;
            openFileDialog1.Filter = "Trade System files (*.xml)|*.xml|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = openFileDialog1.OpenFile()) != null)
                {
                    object o = new TradeSystem();
                    XMLSerializable.DeSerializeObject(ref o, myStream);
                    ITradeSystem ts = o as TradeSystem;

                    ts.SetIDFromLongFileName(openFileDialog1.FileName);

                    myStream.Close();
                    ChangeCurrentTradeSystem(ts);

                    return ts;

                }


            }
            return null;
        }

	}
}
